﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;

using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.DataSourcesRaster;
using System.IO;
using PlanningGIS.Framework;
using PlanningGIS.ManageUtility;

using ESRI.ArcGIS.ConversionTools;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Win.Controls;
using System.Configuration;
using PlanningGIS.ArcGIS;
namespace PlanningGIS.DataConvert
{
    public partial class frmImpRaster : DevComponents.DotNetBar.Office2007Form
    {
        IApplication m_Application = null;
      
        IPropertySet m_PropertySet;
        int intRasterDataset =0;
       // private ResourceTreeView m_ResourceTree;

        private string m_RasterType;
        private TreeNode m_RasterNode;
        public TreeNode RasterNode
        {
            set
            {
                m_RasterNode = value;
                m_RasterType = m_RasterNode.Text;

                ////modified by sheng DEM没有类型
                //if (m_RasterType == "DEM")
                //{
                //    this.Width = 165;
                //}
                //else if (m_RasterType == "DOM")
                //{
                //    this.Width = 338;
                //}
            }
        }

        //public ResourceTreeView ResourceTreeView
        //{
        //    set
        //    {
        //        m_ResourceTree = value;
        //    }
        //}

        public frmImpRaster()
        {
            InitializeComponent();
        }

        public IApplication Application
        {
            set
            {
                m_Application = value;
            }
        }

        #region FormLoad 
        private void frmImpRaster_Load(object sender, EventArgs e)
        {
            //this.cbxType.Items.Clear();
            //if (m_RasterType == "DEM")
            //{
            //    this.cbxType.Enabled = false;
            //}
            //else if (m_RasterType == "DOM")
            //{
            //    this.cbxType.Enabled = true;
            //    string sST = SystemConfig.systemConfigXml.栅格设置.DOM类型;
            //    string[] STs = sST.Split(',');
            //    for (int i = 0; i < STs.Length; i++)
            //    {
            //        this.cbxType.Items.Add(STs[i]);
            //    }
            //    if (this.cbxType.Items.Count > 0)
            //    {
            //        this.cbxType.SelectedIndex = 0;
            //    }
            //}

            List<PlanningGIS.ArcGIS.zjgisWorkspaceType> filters = new List<zjgisWorkspaceType>();
            filters.Add(PlanningGIS.ArcGIS.zjgisWorkspaceType.raster);
            selectGdbDataSource1.EsriDatasetTypeFilters = filters;
            selectGdbDataSource1.WorkspaceType = esriWorkspaceType.esriFileSystemWorkspace;
            selectGdbDataSource1.SelectDataOk = new CmdSelectDataOk(cmdSelectDataOk_Click);

          
        }
        #endregion

        /// <summary>
        /// 确定选择栅格数据集
        /// </summary>
        /// <param name="dataSourceList"></param>
        private void cmdSelectDataOk_Click(List<IDataNode> dataSourceList)
        {
           

            #region 选择栅格要素
            if (dataSourceList == null)
                return;

            foreach (IDataNode dataNode in dataSourceList)
            {
                if (dataNode.WorkspaceType ==  PlanningGIS.ArcGIS.zjgisWorkspaceType.raster)
                {
                    if (dataNode.Open().Workspace.Type != esriWorkspaceType.esriFileSystemWorkspace)
                    {
                       // ZJGIS.ADF.BaseClasses.ControlUtility.ShowInfomationMsgbox("请只选择本地文件栅格要素");
                       
                        return;
                    }
                }
                else
                {
                    MsgHelper.ShowInfomationMsgbox("请只选择本地栅格要素");
                    return;
                }
            }

            m_PropertySet = null;
            //if (m_RasterType == "DEM")
            //{
            //    string value = "";

            //    value = SystemConfigXML.GetConnectString(SystemConfig.systemConfigXml.数据库连接.DEM库连接);

              
            //    m_PropertySet = ConnectionString.GetPropertySet(value);
            //}
            //else if (m_RasterType == "DOM")
            //{
            //    string value = "";

            //    value = SystemConfigXML.GetConnectString(SystemConfig.systemConfigXml.数据库连接.DOM库连接);
              
            //    m_PropertySet = ConnectionString.GetPropertySet(value);
            //}
            #endregion
        }


    

        /// <summary>
        /// 得到rasterdataset的名称
        /// </summary>
        /// <param name="m_Workspace2"></param>
        /// <param name="strName"></param>
        /// <returns></returns>
        private string GetRasterDatasetName(IWorkspace2 m_Workspace2, string strName)
        {
            if (m_Workspace2.get_NameExists(esriDatasetType.esriDTRasterDataset, strName))
            {
                intRasterDataset++;
                string strExt = strName.Substring(strName.Length - 2, 2).ToString();
                int ext = intRasterDataset - 1;
                if (strExt == ("_" + ext.ToString()))
                {
                    return this.GetRasterDatasetName(m_Workspace2, strName.Substring(0, strName.Length - 2) + "_" + intRasterDataset);
                }
                return this.GetRasterDatasetName(m_Workspace2, strName + "_" + intRasterDataset.ToString());
            }
            else
            {
                return strName;
            }
        }

        /// <summary>
        /// 得到要改的raster的名称
        /// </summary>
        /// <param name="m_Workspace2"></param>
        /// <param name="strName"></param>
        /// <returns></returns>
        private string GetRasterDatasetReName(IWorkspace2 m_Workspace2, string strName)
        {
            if (m_Workspace2.get_NameExists(esriDatasetType.esriDTRasterDataset, strName))
            {
                intRasterDataset++;
                string strExt = strName.Substring(strName.Length - 2, 2).ToString();
                int ext = intRasterDataset - 1;
                if (strExt == ("_" + ext.ToString()))
                {
                    return this.GetRasterDatasetReName(m_Workspace2, strName.Substring(0, strName.Length - 2) + "_" + intRasterDataset);
                }
                return this.GetRasterDatasetReName(m_Workspace2, strName + "_" + intRasterDataset.ToString());
            }
            else
            {
                if (intRasterDataset == 0)
                    return strName;
                else
                {
                    int index = strName.LastIndexOf("_");
                    string strRasterName = strName.Substring(0, index);
                    int intCount = int.Parse(strName.Substring(index + 1, strName.Length - index - 1));
                    intCount--;
                    if (intCount == 0)
                        return strRasterName;
                    else
                        return strRasterName + "_" + intCount;
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
           

            try
            {


                List<PlanningGIS.Engine.Controls.IDataNode> datanodes = this.selectGdbDataSource1.DataNodeList;

                if (m_PropertySet != null)
                {
                    //m_frmAddData1.Hide();
                    System.Windows.Forms.Application.DoEvents();
                    #region IDockManager
                    //IDockManager m_DockManager = (m_Application as IFramework).DockManager;
                    //(m_Application as IFramework).DockManager.ActivateDockPanel("日志");
                    //LogPanel logPanel = (m_Application as IFramework).GetControlUserData("日志") as LogPanel;
                    //if (logPanel == null)
                    //{
                    //    logPanel = new LogPanel();
                    //    m_DockManager.AddDockPanel("日志", logPanel, false, esriDockFlags.esriDockBottom);
                    //}
                    //else
                    //{
                    //    m_DockManager.ActivateDockPanel("日志");
                    //}
                    //logPanel.ClearLog();

                    IWorkspaceFactory2 m_Factory = new SdeWorkspaceFactoryClass();
                    IWorkspace m_Workspace = m_Factory.Open(m_PropertySet, 0);
                    IWorkspace2 m_Workspace2 = m_Workspace as IWorkspace2;
                    string strConnect = "Connection to " + m_PropertySet.GetProperty("Server").ToString();
                    string strPath = System.Windows.Forms.Application.StartupPath + "\\Data";
                    DirectoryInfo dinfo = new DirectoryInfo(strPath);
                    FileInfo[] finfos = dinfo.GetFiles(strConnect + "*.sde");
                    for (int i = 0; i < finfos.Length; i++)
                    {
                        finfos[i].Delete();
                    }
                    #endregion

                    #region RASTERCONFIG
                    IWorkspaceFactory2 m_WorkspaceFactory = new SdeWorkspaceFactoryClass();
                    string valuedlg = "";

                    //valuedlg = SystemConfigXML.GetConnectString(SystemConfig.systemConfigXml.数据库连接.DLG库连接); 

                    IFeatureWorkspace m_FeatureWorkspace = null;
                 //   m_FeatureWorkspace= m_WorkspaceFactory.Open(ConnectionString.GetPropertySet(valuedlg), 0) as IFeatureWorkspace;
                
                   IFeatureClass m_FeatureClass = null;
                    try
                    {
                        m_FeatureClass = m_FeatureWorkspace.OpenFeatureClass("RASTERCONFIG");
                        if (m_FeatureClass == null)
                        {
                            string strMsg = "缺少RasterConfig配置图层\r\n请手工创建!";
                            MsgHelper.ShowInfomationMsgbox(strMsg);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        string strMsg = "缺少RasterConfig配置图层\r\n请手工创建!";
                        MsgHelper.ShowInfomationMsgbox(strMsg);
                        return;
                    }

                    this.Cursor = Cursors.WaitCursor;
                    m_Factory.Create(strPath, strConnect, m_PropertySet, 0);
                    string strLocation = strPath + "\\" + strConnect + ".sde";
                    IWorkspaceEdit m_WorkspaceEdit = m_Workspace as IWorkspaceEdit;
                    m_WorkspaceEdit.StartEditing(false);
                    m_WorkspaceEdit.StartEditOperation();
                    #endregion

                    foreach (PlanningGIS.Engine.Controls.IDataNode dataNode in datanodes)
                    {
                        #region MosaicToNewRaster
                        IDataset m_Dataset = dataNode.Open();

                        string strRasterDataset = "";

                        if ((m_RasterType == "DOM"))
                        {
                            strRasterDataset = cbxType.Text + "_" + tenseDtp.Text + "_" + System.IO.Path.GetFileNameWithoutExtension(m_Dataset.Name);
                        }
                        else if (m_RasterType == "DEM")
                        {
                            strRasterDataset = "DEM_" + tenseDtp.Text + "_" + System.IO.Path.GetFileNameWithoutExtension(m_Dataset.Name);
                        }

                        strRasterDataset = GetRasterDatasetName(m_Workspace2, strRasterDataset);
                        intRasterDataset = 0;
                        IRasterBandCollection m_BandCol = m_Dataset as IRasterBandCollection;
                        //logPanel.Log(m_Dataset.Name + "栅格数据入库中......");
                        System.Windows.Forms.Application.DoEvents();
                        RasterToGeodatabase pConversion = new RasterToGeodatabase();
                        pConversion.Input_Rasters = m_Dataset.Workspace.PathName + m_Dataset.Name;
                        pConversion.Output_Geodatabase = strLocation;

                        string strMessage = "";
                        bool success = GeoprocessorHelper.Execute(pConversion, out strMessage);
                        if (success)
                        {
                            intRasterDataset = 0;
                            string strRasterName = GetRasterDatasetReName(m_Workspace2, System.IO.Path.GetFileNameWithoutExtension(m_Dataset.Name));
                            IRasterWorkspaceEx pRasterWorkspaceEx = m_Workspace as IRasterWorkspaceEx;
                            IRasterDataset pRasterDataset = pRasterWorkspaceEx.OpenRasterDataset(strRasterName);
                            (pRasterDataset as IDataset).Rename(strRasterDataset);
                           // logPanel.DoneLog(strMessage);

                         //   logPanel.DoneLog("[" + m_Dataset.Name + "]栅格数据入库完成");
                            System.Windows.Forms.Application.DoEvents();
                            #region RasterDatasetNode
                            //GeoDataNode demNode = new GeoDataNode();
                            //demNode.Name = strRasterDataset;
                            //IDataNode rasterDataNode = new RasterDatasetNode();
                            //rasterDataNode.Path = strRasterDataset;
                            //rasterDataNode.WorkspaceType = zjgisWorkspaceType.sde;
                            //rasterDataNode.PropertySet = m_PropertySet;
                            //rasterDataNode.Name = strRasterDataset;
                            //demNode.DataNode = rasterDataNode;
                            //demNode.Enable = true;
                            //demNode.PropertySet = m_PropertySet;
                            //m_ResourceTree.AddTreeNode(m_RasterNode.Nodes, demNode, m_RasterNode.FullPath);
                            //IResourceNode p_ResourceNode = m_RasterNode.Tag as IResourceNode;
                            //p_ResourceNode.ChildNodes.Add(demNode);
                            #endregion

                            #region IWorkspaceEdit
                            IFeature m_Feature = m_FeatureClass.CreateFeature();
                            m_Feature.set_Value(m_Feature.Fields.FindField("RasterType"), m_RasterType);
                            m_Feature.set_Value(m_Feature.Fields.FindField("TENSE"), tenseDtp.Value);

                            //modified by sheng DOM才有类型
                            if (m_RasterType == "DOM")
                            {
                                m_Feature.set_Value(m_Feature.Fields.FindField("SOURCE"), cbxType.Text);
                            }
                            m_Feature.set_Value(m_Feature.Fields.FindField("NAME"), strRasterDataset);
                            m_Feature.set_Value(m_Feature.Fields.FindField("BAND"), m_BandCol.Count);
                            string strRasterResolution = "1";
                            m_Feature.set_Value(m_Feature.Fields.FindField("Resolution"), strRasterResolution);

                            IWorkspace p_Workspace = m_Dataset.Workspace;
                            IWorkspaceFactory p_WorkspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
                            IFeatureWorkspace p_FeatureWorkspace = (IFeatureWorkspace)p_WorkspaceFactory.OpenFromFile(p_Workspace.PathName, 0);
                            string strShpName = System.IO.Path.GetFileNameWithoutExtension(m_Dataset.Name);
                            IFeatureClass p_FeatureClass = null;// 
                            try
                            {
                                string strShpfile = p_Workspace.PathName + "\\" + strShpName + ".shp";
                                if (File.Exists(strShpfile))
                                    p_FeatureClass = p_FeatureWorkspace.OpenFeatureClass(strShpName);
                            }
                            catch
                            {
                            }
                            if (p_FeatureClass != null)
                            {
                                IFeature p_Feature = p_FeatureClass.Search(null, false).NextFeature();
                                if (p_Feature != null)
                                {
                                    IGeometry p_Geometry = p_Feature.ShapeCopy;
                                    if ((m_FeatureClass as IGeoDataset).SpatialReference != (p_FeatureClass as IGeoDataset).SpatialReference)
                                        p_Geometry.Project((m_FeatureClass as IGeoDataset).SpatialReference);
                                    m_Feature.Shape = p_Geometry;
                                }
                            }
                            else
                            {
                                IRasterDataset p_RasterDataset = m_Dataset as IRasterDataset;
                                IGeometry p_Geometry = GeometryHelper.ExtentToPolygon((p_RasterDataset as IGeoDataset).Extent.XMin, (p_RasterDataset as IGeoDataset).Extent.YMin, (p_RasterDataset as IGeoDataset).Extent.XMax, (p_RasterDataset as IGeoDataset).Extent.YMax) as IGeometry;
                                p_Geometry.Project((m_FeatureClass as IGeoDataset).SpatialReference);
                                try
                                {
                                    m_Feature.Shape = p_Geometry;
                                }
                                catch
                                {
                                  //  logPanel.ErrLog(strRasterDataset + "坐标范围错误，无法记录栅格索引信息");
                                    continue;
                                }
                            }
                            m_Feature.Store();
                            #endregion
                        }
                        else
                        {
                           // logPanel.ErrLog(strMessage);
                           // logPanel.ErrLog("[" + m_Dataset.Name + "]栅格数据入库失败!");
                            System.Windows.Forms.Application.DoEvents();
                        }
                        
                        System.Windows.Forms.Application.DoEvents();
                        #endregion
  
                    }
                    m_WorkspaceEdit.StopEditOperation();
                    m_WorkspaceEdit.StopEditing(true);
                    FileInfo finfo = new FileInfo(strLocation);
                    finfo.Delete();
                    m_RasterNode.Expand();
                    //m_ResourceTree.SaveToDataBase(m_ResourceTree.GetUserResource());
                 //   ZJGIS.ADF.BaseClasses.ControlUtility.ShowInfomationMsgbox("栅格入库完成!");
                }
                this.Close();
            }
            catch (Exception ex)
            {
               // ZJGIS.ADF.BaseClasses.ControlUtility.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

